package pkg

import (
	"context"
	"log"
	"mime/multipart"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

type OSSClient struct {
	Client *oss.Client
	Bucket string
}

func NewOSSClient(endpoint, accessKeyID, accessKeySecret, bucketName string) (*OSSClient, error) {
	// 使用NewStaticCredentialsProvider方法直接设置AK和SK
	provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret)

	// 加载默认配置并设置凭证提供者和区域
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(provider).
		WithRegion(endpoint)

	client := oss.NewClient(cfg)

	return &OSSClient{
		Client: client,
		Bucket: bucketName,
	}, nil
}

// 上传文件，返回文件URL
func (o *OSSClient) UploadFile(file multipart.File, filename string) (string, error) {
	// 创建上传对象的请求
	putRequest := &oss.PutObjectRequest{
		Bucket:       oss.Ptr(o.Bucket),           // 存储空间名称
		Key:          oss.Ptr("test/" + filename), // 对象名称
		StorageClass: oss.StorageClassStandard,    // 指定对象的存储类型为标准存储
		Acl:          oss.ObjectACLPrivate,        // 指定对象的访问权限为私有访问
		Body:         file,
	}

	// 执行上传对象的请求
	_, err := o.Client.PutObject(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	return "test/" + filename, nil
}
